﻿using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Collections.Generic;
using System.Configuration;


/// <summary>
/// WebService の概要の説明です
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
    private bool useTextfileDataBase = false;
    private bool writeDBLog = true;
    public WebService()
    {
        useTextfileDataBase = bool.Parse(ConfigurationManager.AppSettings["UseTextFileDataBase"]);
        writeDBLog = bool.Parse(ConfigurationManager.AppSettings["WriteDBLog"]);

        //デザインされたコンポーネントを使用する場合、次の行をコメントを解除してください 
        //InitializeComponent(); 
    }
    
    private DataBaseAccess GetDataBaseAccess()
    {
        ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"];
        //Console.WriteLine("接続文字列:" + setting.ConnectionString);
        //Console.WriteLine("プロバイダ名:" + setting.ProviderName);

        return new DataBaseAccess(setting.ConnectionString);
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    private string logName = "log.txt";
    private string accessLogName = "accesslog.txt";
    private static object syncObj = new object();

    [SoapDocumentMethod(OneWay=true)]
    [WebMethod]
    public void SendLog(KMessage [] msgs){
	    //DeleteExpired();
        DateTime lastUpdate = DateTime.Now;
        if (useTextfileDataBase)
        {
            try
            {
                lock (syncObj)
                {
                    string logF = Server.MapPath(logName);
                    using (StreamWriter sw = new StreamWriter(logF, true))
                    {
                        foreach (KMessage msg in msgs)
                        {
                            sw.WriteLine(lastUpdate.Ticks.ToString() + sepa[0] + msg.Group + sepa[0] + msg.SenderName + sepa[0] + msg.DestName + sepa[0] + msg.Log);
                        }
                    }
                }
            }
            catch
            {
            }
        }
        else
        {

            foreach (KMessage msg in msgs)
            {
                DataBaseAccess dba = GetDataBaseAccess();
                dba.WriteLog(lastUpdate, msg.Group, msg.SenderName, msg.DestName, msg.Log);
            }

            if (writeDBLog)
            {
                string alogF = Server.MapPath(accessLogName);
                lock (syncObj)
                {
                    using (StreamWriter sw = new StreamWriter(alogF, true))
                    {
                        foreach (KMessage msg in msgs)
                        {
                            sw.WriteLine(lastUpdate.ToString() + " Written by " + msg.SenderName);
                        }
                    }
                }
            }
        }
    }

    static string[] sepa = { "<,>" };
    static char[] trm = { '\n' };

    [WebMethod]
   	public KMessage [] GetLogUpdate(DateTime lastUpdate,string group){//,string senderName){
    	//DeleteExpired();
        List<KMessage> outList;
        if (useTextfileDataBase)
        {
            outList = new List<KMessage>();
            try
            {
                string str = "";
                lock (syncObj)
                {
                    string logF = Server.MapPath(logName);
                    using (StreamReader sr = new StreamReader(logF))
                    {
                        str = sr.ReadToEnd();
                    }
                }
                foreach (string line in str.Split('\n'))
                {
                    //string tline = line.TrimEnd(trm);
                    string tline = line.Substring(0, line.Length - 1);
                    string[] element = tline.Split(sepa, StringSplitOptions.None);
                    //DateTime dt = DateTime.Parse(element[0]);
                    DateTime dt = new DateTime(long.Parse(element[0]));
                    string gr = element[1];
                    string snm = element[2];
                    string dnm = element[3];
                    string com = element[4];
                    if (group.Equals(gr) && lastUpdate < dt)// && !snm.Equals(senderName))
                    {
                        outList.Add(new KMessage(dt, gr, snm, dnm, com));
                    }
                }
            }
            catch
            {
            }
        }
        else
        {
            DataBaseAccess dba = GetDataBaseAccess();
            dba.ReadLog(lastUpdate, group, out outList);

            if (writeDBLog)
            {
                string alogF = Server.MapPath(accessLogName);
                lock (syncObj)
                {
                    using (StreamWriter sw = new StreamWriter(alogF, true))
                    {
                        sw.WriteLine(lastUpdate.ToString() + " Read " + outList.Count.ToString() + " messages");
                    }
                }
            }

        }


        KMessage [] outM = outList.ToArray();
        outList.Clear();
        outList = null;
        return outM;
    }

    public struct KMessage
    {
        public KMessage(DateTime dt, string group, string senderName,string destName, string log)
        {
            Time = dt;
            Group = group;
            SenderName = senderName;
            DestName = destName;
            Log = log;
        }
        public DateTime Time;
        public string Group;
        public string SenderName;
        public string DestName;
        public string Log;
    }

}

